package com.huiyeji.xlsx;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FileProcessExecutor {

    public static final String PROCESSOR_NAME = "processorName";

    private static final Logger logger = LoggerFactory.getLogger(FileProcessExecutor.class);

    private static final Map<String,FileProcessor> PROCESSORS = new HashMap<String, FileProcessor>();

    /**
     * 文件处理执行器
     * @param file
     * @param params
     * @return
     */
    public static Workbook processExecute(MultipartFile file, Map<String, Object> params) {
        String processorName = (String) params.get(PROCESSOR_NAME);
        if (!StringUtils.hasLength(processorName)){
            throw new XLSXValidationException("未指定文件处理器名称[processorName]，无法处理文件");
        }

        //获得文件处理器
        FileProcessor fileProcessor = PROCESSORS.get(processorName);
        if (fileProcessor == null){
            throw new XLSXValidationException("未找到文件处理器["+processorName+"]，无法处理文件");
        }

        //文件处理
        return fileProcessor.process(file, params);
    }

    protected static void registerProcessor(Processor processorAnno, FileProcessor processor) {
        if (!StringUtils.hasLength(processorAnno.name())){
            logger.info("处理器名称为空，注册失败");
            return;
        }

        if (PROCESSORS.containsKey(processorAnno.name())){
            logger.info("处理器["+processorAnno.name()+"]已存在，注册失败");
            return;
        }

        PROCESSORS.put(processorAnno.name(), processor);
    }

    public static Set<String> getProcessorNames() {
        return PROCESSORS.keySet();
    }

    public static FileProcessor getProcessor(String processorName) {
        return PROCESSORS.get(processorName);
    }
}
